package com.shundr.user;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.service.PhoneReceiver;
import com.shundr.frame.service.PhoneReceiver.SmsHandler;
import com.shundr.frame.service.SmsObserver;
import com.shundr.frame.util.StringUtil;
import com.shundr.user.http.UserRequest;

/**
 * 找回密码
 * RetrievePasswordActivity
 * 
 * @author luo 2015-5-11 上午11:19:12 
 * @version 1.0.0
 *
 */
public class RetrievePasswordActivity extends BaseActivity implements OnClickListener,SmsHandler{
	private View vGetCaptcha;
	private View vSetNewPassword;
	private EditText etUserName;
	private EditText etCode;
	private Button btnClearUserName;
	private Button btnGetCaptcha;
	private Button btnNextStep;
	
	private EditText etPassword1;
	private EditText etPassword2;
	private Button btnClear1;
	private Button btnClear2;
	private Button btnSetNewp;
	private Timer mTimer;
	private static final int TOTAL = 60;
	private int timerTotal = TOTAL;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1999:
				mTimer = new Timer();
				mTimer.schedule(new TimerTask() {
					
					@Override
					public void run() {
						mHandler.sendEmptyMessage(2000);
					}
				}, 0,1000);
				break;
			case UserRequest.RESER_USERPSW_SUCCESSED:
				ToastHelper.toastShort(mContext, msg.obj.toString());
				ProgressDialogHelper.dismiss();
				finish();
				break;
			case UserRequest.CHECK_CAPTCHA_SUCCESSED:
				ProgressDialogHelper.dismiss();
				vGetCaptcha.setVisibility(View.GONE);
				vSetNewPassword.setVisibility(View.VISIBLE);
				if (mTimer != null) {
					timerTotal=TOTAL;
					btnGetCaptcha.setText("获取验证码");
					mTimer.cancel();
					mTimer = null;
				}
				break;
			case 2000:
				if(timerTotal != 0){
					timerTotal = timerTotal - 1;
					btnGetCaptcha.setText(timerTotal + "秒后重新获取");
					btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
					btnGetCaptcha.setEnabled(false);
				}else{
					timerTotal = TOTAL;
					btnGetCaptcha.setText("点击重新获取");
					btnGetCaptcha.setBackgroundResource(R.drawable.btn_orange_light_selector);
					btnGetCaptcha.setEnabled(true);
					mTimer.cancel();
					mTimer = null;
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, msg.obj.toString());
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_retrieve_passwod);
		vGetCaptcha=(View)findViewById(R.id.layout_get_captcha);
		vSetNewPassword=(View)findViewById(R.id.layout_set_new_password);
		etUserName=(EditText)findViewById(R.id.et_username);
		etCode=(EditText)findViewById(R.id.et_code);
		btnClearUserName=(Button)findViewById(R.id.btn_name_clear);
		btnGetCaptcha=(Button)findViewById(R.id.btn_get_auth_code);
		btnNextStep=(Button)findViewById(R.id.btn_next_step);
		
		btnClearUserName.setOnClickListener(this);
		btnGetCaptcha.setOnClickListener(this);
		btnNextStep.setOnClickListener(this);
		
		etPassword1=(EditText)findViewById(R.id.et_account1);
		etPassword2=(EditText)findViewById(R.id.et_account2);
		btnClear1=(Button)findViewById(R.id.btn_password_clear1);
		btnClear2=(Button)findViewById(R.id.btn_password_clear2);
		btnSetNewp=(Button)findViewById(R.id.set_new_psd_request);
		
		btnClear1.setOnClickListener(this);
		btnClear2.setOnClickListener(this);
		btnSetNewp.setOnClickListener(this);
		textChange();
		
		initSmsObserver();
	}
	
	private SmsObserver mSmsObserver;
	private void initSmsObserver(){
		mSmsObserver = new SmsObserver(this, new Handler(), etCode);
		// 注册短信变化监听
		getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mSmsObserver);
	}
	
	@Override
	protected void onResume() {
		PhoneReceiver.mSmsListeners.add(this);
		super.onResume();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_name_clear:
			etUserName.setText("");
			break;
		case R.id.btn_get_auth_code:
			new UserRequest(mContext, mHandler).getAuthCode(etUserName.getText().toString(), "1");
			mHandler.sendEmptyMessage(1999);
			break;
		case R.id.btn_next_step:
			checkCaptcha();
			break;
		case R.id.btn_password_clear1:
			etPassword1.setText("");
			break;
		case R.id.btn_password_clear2:
			etPassword2.setText("");
			break;
		case R.id.set_new_psd_request:
			setNewPassword();
			break;
		default:
			break;
		}
	}
	
	private void checkCaptcha(){
		try {
			String phone=etUserName.getText().toString().trim();
			if(StringUtil.isNull(phone)){
				ToastHelper.toastShort(mContext, "请输入手机号码");
				return;
			}
			if(!StringUtil.isMobileNO(phone)){
				ToastHelper.toastShort(mContext, "请输入正确格式的手机号码");
				return;
			}
			String code=etCode.getText().toString().trim();
			if(StringUtil.isNull(code)){
				ToastHelper.toastShort(mContext, "请输入验证码");
				return;
			}
			if((code).length()<6||(code).length()>6){
				ToastHelper.toastShort(mContext, "请输入正确的验证码");
				return;
			}
			ProgressDialogHelper.show(mContext, "检查验证码...");
			new UserRequest(mContext, mHandler).checkCaptcha(phone, code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setNewPassword(){
		if(StringUtil.isNull(etPassword1.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入6到16位非空格密码");
			etPassword1.setText("");
			return;
		}
		if(etPassword1.getText().toString().length() < 6){
			ToastHelper.toastShort(mContext, "输入的密码长度太短,请重新输入");
			return;
		}
		if(etPassword1.getText().toString().length() > 16){
			ToastHelper.toastShort(mContext, "输入的密码长度太长,请重新输入");
			return;
		}
		if(!StringUtil.isEqual(etPassword1.getText().toString(), etPassword2.getText().toString())){
			ToastHelper.toastShort(mContext, "密码不一致,请重新输入");
			etPassword2.setText("");
			return;
		}
		ProgressDialogHelper.show(mContext, "正在重置密码...");
		new UserRequest(mContext, mHandler).resetUserPsw(etUserName.getText().toString(), etPassword1.getText().toString());
	}
	
	private void textChange(){
		etUserName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnClearUserName.setVisibility(View.VISIBLE);
				}else{
					btnClearUserName.setVisibility(View.GONE);
				}
				if(s.length() == 11){
					if(StringUtil.isMobileNO(s.toString())){
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_orange_light_selector);
						btnGetCaptcha.setEnabled(true);
					}else{
						ToastHelper.toastShort(mContext, "请输入正确的手机号");
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
						btnGetCaptcha.setEnabled(false);
					}
				}else{
					btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
					btnGetCaptcha.setEnabled(false);
				}
				if(s.length()>=12){
					ToastHelper.toastShort(mContext, "请输入正确的手机号");
				}
			}
		});
		
		etPassword1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnClear1.setVisibility(View.VISIBLE);
				}else{
					btnClear1.setVisibility(View.GONE);
				}
			}
		});
		
		etPassword2.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnClear2.setVisibility(View.VISIBLE);
				}else{
					btnClear2.setVisibility(View.GONE);
				}
				
			}
		});
	}

	@Override
	protected void onDestroy() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		getContentResolver().unregisterContentObserver(mSmsObserver);
		PhoneReceiver.mSmsListeners.remove(this);
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		if(vSetNewPassword.isShown()){
			vSetNewPassword.setVisibility(View.GONE);
			vGetCaptcha.setVisibility(View.VISIBLE);
		}else{
			finish();
		}
	}

	@Override
	public void onReceived(String sms) {
		etCode.setText(sms);
	}
}
